//
//  QDGuideTableViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/4/29.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit

/// 指南的列表控制器
final class QDGuideTableViewController: NWTableViewController {

    /// 指南列表
    var guides = [QDImageListModel]()
    
    override func loadPropertysAtInitialization() {
        super.loadPropertysAtInitialization()
        headerRefreshEnable = false
        footerRefreshEnable = false
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.rowHeight = QDGuideTableViewCell.cellHeight
        tableView.contentInset.top = 10
        navigationItem.title = "指南"
        // 请求指南列表
        requestGuides()
    }
    
    override func registerTableViewCellsAndReusableView() {
        tableView.register(QDGuideTableViewCell.self, forCellReuseIdentifier: "cell")
    }
    
    override var tableViewBackgroundColor: UIColor { return 252.ritl_color }
}


extension QDGuideTableViewController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.guides.count
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    }
    
    
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        // 是指南样式
        guard let guideCell = cell as? QDGuideTableViewCell else {
            return
        }
        
        let guide = guides[indexPath.row]
        guideCell.titleLabel.text = guide.title
        guideCell.topImageView.kf.setImage(with: URL(string: guide.imgUrl))
    }
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let guide = guides[indexPath.row]
        pushToShareWebViewController(url: guide.url, shareTitle: guide.title, title: "详情")
    }
}


extension QDGuideTableViewController {
    
    /// 请求公告列表
    private func requestGuides() {
        
        QDNetworkingManager.request(url: guideUrl, isArray: true, arraySuccess: { (msg, datas) in
          
            guard let guides = [QDImageListModel].deserialize(from: datas) as? [QDImageListModel] else {
                return
            }
            
            self.guides = guides
            //刷新
            self.tableView.reloadData()
            // 无公告
            if guides.count == 0 { self.view.showTextHUD(text: "暂无公告") }
            
        }) { (msg, type) in
            
            self.view.showTextHUD(text: msg)
        }
    }
    
}
